package cn.kgc.springbootdemo.util;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.kgc.springbootdemo.constant.CommonConstants;
import cn.kgc.springbootdemo.entity.User;
import com.auth0.jwt.JWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <h3>springbootdemo</h3>
 * <p>根据toke获取当前登录人</p>
 *
 * @author : DongZeJian
 * @date : 2020-07-17 15:59
 **/
@Component
public class TokenUtil {

    @Autowired
    private RedisUtil redisUtil;

    public String getTokenUserID(){
        String token = getToken();// 从 http 请求头中取出 token
        Validator.validateNotEmpty(token,"token不能为空");
        return JWT.decode(token).getAudience().get(0);
    }

    private HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }

    public String getToken(){
        return getRequest().getHeader("Authorization");
    }

    public User getUser(){
        String token = getToken();// 从 http 请求头中取出 token
        if (StrUtil.isBlank(token)){
            return null;
        }
        String userId = JWT.decode(token).getAudience().get(0);
        String user = redisUtil.get(CommonConstants.COOKIE_NAME_TOKEN + ":" + userId + token);
        if (StrUtil.isNotBlank(user)){
            return JSONUtil.toBean(user, User.class);
        }
        return null;
    }

    public boolean lives(){
        String token = getToken();// 从 http 请求头中取出 token
        if (StrUtil.isBlank(token)){
            return false;
        }
        String userId = JWT.decode(token).getAudience().get(0);
       return redisUtil.expire(CommonConstants.COOKIE_NAME_TOKEN + ":" + userId + token,60*10);
    }
}
